/**
** 弹出对话框 插件
**author: ericever
**create time: 2015-8-4
**/
;(function( $, window, document,undefined){
    'use strict';
    var defaults = {
        title:"",
        label:"",
        type:"simple",
        id:"",
        body:"",
        step:null,
        vidList:null,
        hwd:null
    };
    var Dialog = function (element, options) {
        var self = this;
        var savetags = [];
        this.$element = $(element);
        this.config = $.extend(true,{}, defaults, options);
        var id = this.config.id;
        var label = this.config.label;
        var title = this.config.title;
        var hwd = this.config.hwd;
        var I18N = window.I18N;
        //给视频选择弹出窗口用的
        var cover   = '<div class="modal-content step-one">'
                    + '<div class="modal-header">'
                    + '<button class="close" data-dismiss="modal" aria-label="Close">'
                    + '<span aria-hidden="true">&times;</span></button>'
                    + '<h4 class="modal-title">'
                    + I18N.getText('createAd', 'selectVideo')
                    + '</h4>'
                    + '</div>'
                    + '<div class="modal-body"><ul class="list-group" style="height: auto;"> <li class="list-group-item">'
                    + '<strong>'
                    + I18N.getText('createAd', 'appLabels')
                    + '</strong>'
                    + '<select class="dia-video-app" multiple style="width:400px;"></select> </li> </ul><ul class="vid-list-box"></ul></div>'
                    + '<div class="modal-footer">'
                    + '  <button type="button" class="btn btn-primary" id="next">'
                    + I18N.getText('createAd', 'next')
                    + '</button>'
                    + '</div>'
                    + '</div>';

        function build(){
            if($(element).attr("id") == id){
                if(id=="videos" && self.config.step){
                    $(element).find("div.step-one").addClass("hidden");
                    $("button#preview").addClass("hidden");
                }else if(id=="videos"){
                    $(element).find("div.step-one").removeClass("hidden");
                    $("button#preview").removeClass("hidden");
                }
				if(id!="messageModal"){
					return $(element);
				}
            }else{
                destory();
                if(id=="jumpto"){
                    var html = '<div class="modal-dialog"><div class="modal-content"><div class="alert alert-success" role="alert"><i class="glyphicon glyphicon-bullhorn"></i> <strong>发布成功!</strong> 即将为您跳转到发布列表页</div></div></div>';
                    $(element).attr("id",id);
                    $(element).html(html);
                    return $(element);
                }
            }
            $(element).attr("id",id);
            var str = '<div class="modal-dialog">\
                '+(id=='videos'?cover:'')+'\
                <div class="modal-content step-two">\
                  <div class="modal-header">\
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">\
                    <span aria-hidden="true">&times;</span></button>\
                    <h4 class="modal-title">'+title+'</h4>\
                  </div>\
                  <div class="modal-body"></div>\
                  <div class="modal-footer">\
                    '+(id=='videos'?'<button class="btn btn-primary" id="preview">'+I18N.getText('createAd', 'prev')+'</button>':'')+'\
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="ok">'+I18N.getText('createAd', 'confirm')+'</button>\
                    <button type="button" class="btn btn-default" data-dismiss="modal">'+I18N.getText('createAd', 'cancel')+'</button>\
                  </div>\
                </div>\
              </div>';
            var node = $(str);
            node.find(".step-two div.modal-body").html('<label>'+label+'<input type="text"></label>');
            if(self.config.body!="") node.find(".step-two div.modal-body").html(self.config.body);
            $(element).append(node);
            if(id=='picc'){
                node.find('.square-priority-label').show();
                if(sessionStorage.isSupportInstagram=='N'){
                    node.find('.fa-arrow-up').removeClass('fa-arrow-up').addClass('fa-arrow-down');
                }
            }else{
                node.find('.square-priority-label').hide();
            }
			if(id == "messageModal"){
				$(element).find("div.modal-footer").remove();
				$(element).find("div.modal-dialog").attr("role","document").addClass("modal-lg");
			}
            $("button#ok").click(function(){
                if(id.indexOf("saveslogan")!=-1){//保存广告语
                    if (-1 == $(".save-adword-lan-drop").select2("val")){
                        warning($("div[name='save-lang-drop']"));
                        return false;
                    }

                    $(element).trigger("ok",{
                        desc:$(element).find("textarea").val(),
                        languageId:$(".save-adword-lan-drop").select2("data")[0].id,
                        language:$(".save-adword-lan-drop").select2("data")[0].text
                    });
                }else if(id == "selectslogan"){//选择广告词
                    if($(element).find("input[name='adword-select']:checked").length<=0) {
                        return false;
                    }
                    var txt = $(element).find("input[name='adword-select']:checked").attr('adword');
                    $(element).trigger("ok",{word:txt});
                }else if(id== "importint"){
                    var _importInts = $(element).find("select.choosed-ints").select2("data");
                    $(element).trigger("ok", {importInts : _importInts});
                }else if(id == 'saveint' || id == 'saveuser'){ //保存兴趣词 && 保存定位模板
                    var nameInput = $(element).find("label>input[type]"),name = nameInput.val();
                    if(name.trim()==""){
                        warning(nameInput);
                        return false;
                    } else {
                        $(element).trigger("ok",{name:name});
                    }
                    nameInput.val('');
                } else if(id.indexOf("save")!=-1){
                    if($(element).find("label>input[type]").val().trim()=="") return false;
                    var nameInput = $(element).find("label>input[type]"),name = nameInput.val();
                    nameInput.val('');
                    $(element).trigger("ok",{name:name});
                }else{//素材选择
                    var eles = $(element).find("ul.pics-box>li.active");//jquery数组对象
                    if(eles==undefined || eles.length==0){
                        _alert2(I18N.getText('createAd', 'selectMaterial'));
                        return false;
                    }
                    var target = $('input[name=asset1]:checked').parent().data('target');

                    var len = $('#carousels .container-fluid.container-fluid-car.active').length;//轮播图判断
                    if(target=='#carousel' && len<3){
                        _alert2(I18N.getText('createAd', 'minSelectSlider', 3));
                        return false;
                    }
                    if(eles.length==0) return false;
                    $(this).parent().parent().siblings().removeClass("hidden");
                    //var vsrc = $("ul.vid-list-box>li>img").attr("src");
                    var vidNode = $("ul.vid-list-box>li.active");
                    $(element).trigger("ok",{imgs:eles,vid:vidNode,hwd:hwd});
                }
            });
            $("button#next").click(function(){
                $(this).parent().parent().addClass("hidden");
                $(this).parents('.modal-dialog').find('.filter-tool').addClass("hidden");
                $(this).parents('.modal-dialog').find('.filter-tool').next().addClass("hidden");
                $(this).parents('.modal-dialog').find('.pics-box').removeClass("hidden");

//                 $(this).parents('.modal-dialog').find('.filter-tool').addClass("hidden");
            });
            $("button#preview").click(function(){
                $(this).parent().parent().siblings().removeClass("hidden");
            });
        };

        /**
        *
        * 从kit中得到的alert2方法
        **/
        function _alert2 (msg) {
            var t = '<div class="alert alert-warning" role="alert" id="http-error"></div>';
            var ta = $("#http-error");
            if (!ta[0]) {
                $('body').append(t);
                ta = $("#http-error");
            }
            ta.text(msg);
            ta.removeClass("anim_image_glow2").addClass("anim_image_glow2");
            setTimeout(function() {
                ta.removeClass("anim_image_glow2");
            }, 3000);
        }

        function warning (ta){
            ta.focus();
            ta.removeClass("anim_image_glow").addClass("anim_image_glow");
            $(ta).on("webkitAnimationEnd mozAnimationEnd MSAnimationEnd animationend",function(){
                $(this).removeClass("anim_image_glow");
            });
        }

        function destory(){
            $(element).empty();
        };

        function lastTime(tag){
            self.config.capacity = $(element).find(tag).text()||self.config.capacity;
        }

        this.startup = function(){
            build();
        }
    };

    /***
    ** 入口
    **/
    $.fn.dialog = function(options){
        var bd = new Dialog(this,options);
        bd.startup();
        return this;
    }
}(jQuery, window, document));
